﻿using System;
using System.Collections.Generic;
using Shell.Build;

namespace Shell.Ioc
{
    public class IocBuildersExtension : IShellExtension //TODO internal
    {
        private readonly Stack<StagedBuilder> registeredbuilders;

        public IocBuildersExtension()
        {
            this.registeredbuilders = new Stack<StagedBuilder>();
        }

        public Guid Identity
        {
            get { return IShellExtensionIdentities.IocBuildersExtension; }
        }

        public ShellExtensionContext Context { get; private set; }

        public void Initialize(ShellExtensionContext context)
        {
            this.Context = context;

            var constructorAnalyst = new StagedBuilder(BuildStage.PreCreation, new ConstructorAnalyst());
            this.Context.BuildChainMaker.Add(constructorAnalyst.Stage, constructorAnalyst.Builder);
            this.registeredbuilders.Push(constructorAnalyst);

            var buildPlanExecutor = new StagedBuilder(BuildStage.Creation, new BuildPlanExecutor());
            this.Context.BuildChainMaker.Add(buildPlanExecutor.Stage, buildPlanExecutor.Builder);
            this.registeredbuilders.Push(buildPlanExecutor);
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                while (this.registeredbuilders.Count > 0)
                {
                    var stagedBuilder = this.registeredbuilders.Pop();
                    this.Context.BuildChainMaker.Remove(stagedBuilder.Stage, stagedBuilder.Builder);
                }
                this.Context = null;
            }
        }

        private class StagedBuilder
        {
            public StagedBuilder(BuildStage stage, IBuilder builder)
            {
                this.Stage = stage;
                this.Builder = builder;
            }

            public BuildStage Stage { get; private set; }

            public IBuilder Builder { get; private set; }
        }
    }
}
